using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
namespace WaterQualityReportSystem.utils
{
    public class RestClient
    {
        private string BaseUri;
        public RestClient(string baseUri)
        {
            BaseUri = baseUri;
        }

        public RestClient()
        {
        }

        #region Delete方式
        public string Delete(string data, string uri)
        {
            return CommonHttpRequest(data, uri, "DELETE",null);
        }

        public string Delete(string uri)
        {
            //Web访问对象64
            string serviceUrl = null;

            if (uri.ToLower().StartsWith("http://") == false && uri.ToLower().StartsWith("https://") == false)
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            else
            {
                serviceUrl = uri;
            }

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Method = "DELETE";
            // 获得接口返回值68
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }
        #endregion

        #region Put方式
        public string Put(string data, string uri)
        {
            return CommonHttpRequest(data, uri, "PUT", null);
        }
        #endregion

        #region POST方式实现

        public string Post(string data, string uri,Dictionary<String, String> headerParam)
        {
            return CommonHttpRequest(data, uri, "POST",headerParam);
        }

        public string CommonHttpRequest(string data, string uri, string type,Dictionary<String,String> headerParams)
        {
            //Web访问对象，构造请求的url地址
            string serviceUrl = uri;


            //构造http请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //转成网络流
            byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data);
            //设置
            myRequest.Method = type;
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;

            if (headerParams != null && headerParams.Count > 0)
            {
                foreach (String key in headerParams.Keys) {
                    String value = headerParams[key];
                    myRequest.Headers.Add(key, value);
                }
            }

            // 发送请求
            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();
            // 获得接口返回值
            //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = reader.ReadToEnd();
            //reader.Close();
            //myResponse.Close();

            try
            {
                // 发送请求并获取响应
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

                if (myResponse.StatusCode == HttpStatusCode.InternalServerError)
                {
                    // 处理 500 错误情况
                    using (Stream responseStream = myResponse.GetResponseStream())
                    {
                        // 解析响应流中的内容以获取错误信息
                        // 这可能需要根据具体的 API 进行自定义解析

                        // 示例：读取响应流的文本内容
                        string errorMessage = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
                        return errorMessage;
                    }
                }
                else
                {
                    // 处理其他状态码的情况
                    // 继续处理正常的响应

                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                    string ReturnXml = reader.ReadToEnd();
                    reader.Close();
                    myResponse.Close();
                    return ReturnXml;
                }
            }
            catch (WebException ex)
            {
                // 处理 WebException 异常
                System.Diagnostics.Debug.WriteLine("发生网络异常: " + ex.Message);

                if (ex.Response != null)
                {
                    // 尝试获取错误响应
                    using (Stream responseStream = ex.Response.GetResponseStream())
                    {
                        // 解析响应流中的内容以获取错误信息
                        // 这可能需要根据具体的 API 进行自定义解析

                        // 示例：读取响应流的文本内容
                        string errorMessage = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
                        return errorMessage;
                    }
                }
                else
                {
                    return "未知原因";
                }
            }
        }
        #endregion

        #region GET方式实现
        public string Get(string uri)
        {
            //Web访问对象64
            string serviceUrl = null;

            if (uri.ToLower().StartsWith("http://") == false && uri.ToLower().StartsWith("https://") == false)
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            else
            {
                serviceUrl = uri;
            }

            //构造一个Web请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            // 获得接口返回值68
            //获取web请求的响应的内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

            //通过响应流构造一个StreamReader
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }
        #endregion
    }
}


